﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;

namespace WebUI.Controls
{
    public partial class PurchaseOrderDetailsCtrl : BaseListControl, IListControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);
        }

        public int DumpID
        {
            get
            {
                if (ViewState[ClientID + "_DumpID"] == null || !(ViewState[ClientID + "_DumpID"] is int))
                    ViewState[ClientID + "_DumpID"] = 0;
                return (int)ViewState[ClientID + "_DumpID"];
            }
            set { ViewState[ClientID + "_DumpID"] = value; }
        }

        public Decimal TotalAmt
        {
            get
            {
                if (ViewState[ClientID + "_TotalAmt"] == null || !(ViewState[ClientID + "_TotalAmt"] is Decimal))
                    ViewState[ClientID + "_TotalAmt"] = 0;
                return (Decimal)ViewState[ClientID + "_TotalAmt"];
            }
            set { ViewState[ClientID + "_TotalAmt"] = value; }
        }

        public Decimal TotalGST
        {
            get
            {
                if (ViewState[ClientID + "_TotalGST"] == null || !(ViewState[ClientID + "_TotalGST"] is Decimal))
                    ViewState[ClientID + "_TotalGST"] = 0;
                return (Decimal)ViewState[ClientID + "_TotalGST"];
            }
            set { ViewState[ClientID + "_TotalGST"] = value; }
        }

        public PurchaseOrderDetails OrderItems
        {
            get { return (PurchaseOrderDetails)SourceObject; }
            set { SourceObject = value; }
        }

        #region IListControl Members

        public void DeleteCheckedItems()
        {
            String checkedItemID = "";
            for (int i = 0; i < grid.Items.Count; i++)
            {
                DataGridItem item = grid.Items[i];
                Control ctrl = item.FindControl("cbSelect");
                if (ctrl != null && ctrl is CheckBox && ((CheckBox)ctrl).Checked && ((CheckBox)ctrl).Attributes["ItemID"] != null)
                    checkedItemID += ((CheckBox)ctrl).Attributes["ItemID"].ToString() + ",";
            }
            if (checkedItemID != "")
                checkedItemID = checkedItemID.Remove(checkedItemID.Length - 1);
            checkedItemID = "(" + checkedItemID + ")";

            String oldFilter = Filter;
            if (!String.IsNullOrEmpty(oldFilter))
                Filter = Filter + " and (" + PurchaseOrderDetails.ColumnNames.ID + " in " + checkedItemID + ")";
            else
                Filter = PurchaseOrderDetails.ColumnNames.ID + " in " + checkedItemID;

            OrderItems.Rewind();
            while (OrderItems.RowCount > 0)
            {
                OrderItems.MarkAsDeleted();
                OrderItems.MoveNext();
            }

            //if (!SaveOnCommit)
            //    OrderItems.Save();

            Filter = oldFilter;
            UpdateTotalAmt();
        }

        public void UpdateTotalAmt()
        {
            TotalGST = 0;
            TotalAmt = 0;

            //if (OrderItems == null)
            //    return;

            //TotalGST = 0;
            //TotalAmt = 0;

            if (SourceObject != null && SourceObject.RowCount > 0 && !SourceObject.IsColumnNull("GST") && !SourceObject.IsColumnNull("TotalCost"))
            {
                SourceObject.Rewind();
                for (int i = 0; i < SourceObject.RowCount; i++)
                {
                    TotalAmt += (decimal)SourceObject.GetColumn("TotalCost");
                    TotalGST += (decimal)SourceObject.GetColumn("GST");
                    SourceObject.MoveNext();
                }
            }
        }

        public void DeleteSelectedItem()
        {
            throw new NotImplementedException();
        }

        public void AddNewItem(MyGeneration.dOOdads.SqlClientEntity newItem)
        {
            throw new NotImplementedException();
        }

        public void UpdateItem(MyGeneration.dOOdads.SqlClientEntity updatedItem)
        {
            throw new NotImplementedException();
        }

        #endregion

        protected override void grid_OnItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Footer)
            {
                e.Item.Cells[6].Text = TotalGST == null ? string.Format("{0:C}", 0) : string.Format("{0:C}", TotalGST);
                e.Item.Cells[7].Text = TotalAmt == null ? string.Format("{0:C}", 0) : string.Format("{0:C}", TotalAmt);
                e.Item.Cells[6].Attributes.Add("align", "right");
                e.Item.Cells[7].Attributes.Add("align", "right");
            }
        }

        public void AddNonIMEIProduct(int productID, int qty)
        {
            String oldFilter = "";
            try
            {
                if (OrderItems == null)
                    OrderItems = new PurchaseOrderDetails();

                oldFilter = OrderItems.Filter;
                OrderItems.Filter = "ProductID = " + productID + " and (IMEI = '' or IMEI is NULL)";
                if (OrderItems.RowCount <= 0)
                    OrderItems.AddNew();
                else
                    qty += OrderItems.Quantity;

                Products prod = new Products();
                prod.LoadByPrimaryKey(productID);

                if (prod.RowCount > 0)
                {
                    Decimal cost = prod.Cost;
                    Decimal total = (Decimal)(cost * qty);
                    Decimal gst = prod.GST ? Math.Round(total * SysVars.GST / (SysVars.GST + 100), 2) : 0;

                    OrderItems.ID = --DumpID;
                    OrderItems.AddInfoPlus(0, prod.ID, "", prod.ProductName, qty, cost, gst);
                }
                else
                {
                    OrderItems.Filter = oldFilter;
                    ShowErrorMessage(grid, ("(*) Product is not available."));
                    return;
                }

                OrderItems.Filter = oldFilter;
                UpdateTotalAmt();
                Refresh();
            }
            catch (Exception ex)
            {
                OrderItems.Filter = oldFilter;
                ErrorLog.WriteToFile("PurchaseOrderDetailsCtrl.ascx.cs", "AddNonIMEIProduct", ex.Message);
                ShowErrorMessage(grid, "(*) Error: " + ex.Message);
            }
        }

        public void AddIMEI(string[] imeis, int productID)
        {
            
            String oldFilter = "";
            try
            {
                Products prod = new Products();
                prod.LoadByPrimaryKey(productID);
                oldFilter = OrderItems.Filter;
                for (int i = 0; i < imeis.Length; i++)
                {
                    if (OrderItems == null)
                        OrderItems = new PurchaseOrderDetails();

                    OrderItems.Filter = "IMEI = '" + imeis[i] + "'";
                    if (OrderItems.RowCount > 0)
                    {
                        OrderItems.Filter = oldFilter;
                        if (OrderItems.IsColumnNull("ID"))
                            OrderItems.MarkAsDeleted();
                        UpdateTotalAmt();
                        Refresh();
                        ShowErrorMessage(grid, String.Format("(*) IMEI {0} has already been added. Please choose another one.", imeis[i]));
                        return;
                    }
                    else
                    {
                        OrderItems.Filter = oldFilter;
                        OrderItems.AddNew();
                    }

                    View_ProductDetails prodDetails = View_ProductDetails.GetAvailableProductDetailsByIMEI(imeis[i]);
                    if (prodDetails.RowCount > 0)
                    {
                        OrderItems.Filter = oldFilter;
                        if (OrderItems.IsColumnNull("ID"))
                            OrderItems.MarkAsDeleted();
                        UpdateTotalAmt();
                        Refresh();
                        ShowErrorMessage(grid, (String.Format("(*) IMEI {0} has been purchased before! Can not purchase again!", imeis[i])));
                        return;
                    }
                    else
                    {
                        Decimal cost = prod.Cost;
                        Decimal total = (Decimal)(cost * 1);
                        Decimal gst = prod.GST ? Math.Round(total * SysVars.GST / (SysVars.GST + 100), 2) : 0;

                        OrderItems.ID = --DumpID;
                        OrderItems.AddInfoPlus(0, productID, imeis[i], prod.ProductName, 1, cost, gst);
                    }
                }

                OrderItems.Filter = oldFilter;
                UpdateTotalAmt();
                Refresh();

            }
            catch (Exception ex)
            {
                if (OrderItems.IsColumnNull("ID"))
                    OrderItems.MarkAsDeleted();
                OrderItems.Filter = oldFilter;
                ErrorLog.WriteToFile("PurchaseOrderDetailsCtrl.ascx.cs", "AddIMEI", ex.Message);
                ShowErrorMessage(grid, "(*) Error: " + ex.Message);
            }
        }
    }
}